package com.lh.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

/**
 * jwt的工具类
 */
@Slf4j
public class JwtUtils {

    /**
     * 创建token
     */
    public static String sign(String username, String secret) {
        // 声明使用什么算法加密和盐
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带用户信息
        return JWT.create()
                .withClaim("username", username)
                .withClaim("loginTime", System.currentTimeMillis())
                .sign(algorithm);
    }

    /**
     * 校验token是否正确
     */
    public static boolean verify(String token, String username, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier jwtVerifier = JWT.require(algorithm)
                    .withClaim("username", username)
                    .build();
            DecodedJWT verify = jwtVerifier.verify(token);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    /**
     * 获取token中的有效信息
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT decode = JWT.decode(token);
            return decode.getClaim("username").asString();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

}
